//
//  ProductViewController.swift
//  lottery
//
//  Created by admin on 16/2/4.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
let collectionIdentifier = "jinCollectionCell"
class ProductViewController: UICollectionViewController {
    // 产品数据模型数组
    lazy var products:[Product] = Product.instanceOfFile()
    // 重写构造方法
    override init(collectionViewLayout layout: UICollectionViewLayout) {
        // cell的大小是通过Layout来控制
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(100, 120)
        super.init(collectionViewLayout : layout)
    }
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName : nibNameOrNil, bundle : nibBundleOrNil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        // 和tableView不同的是，需要先注册cell
//        self.collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
        self.collectionView?.registerNib(UINib(nibName: "JinCollectionCell", bundle: NSBundle.mainBundle()), forCellWithReuseIdentifier: collectionIdentifier)
    }
    // 返回分组数
    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    // 返回分组数据条数
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.products.count
    }
    // 返回cell
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 从缓冲池中获取cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionIdentifier, forIndexPath: indexPath) as! JinCollectionCell
        cell.product = self.products[indexPath.row]
        return cell
    }
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let appliction = UIApplication.sharedApplication()
        // 打开url
        appliction.openURL(NSURL(string: self.products[indexPath.row].url)!)
    }
}
